'use strict';

const {
	Controller
} = require('uni-cloud-router');
const dbcmd = uniCloud.database().command;
const $ = dbcmd.aggregate;

module.exports = class InvoiceController extends Controller {
	// 发票列表
	async invoiceList() {
		const response = {
			code: 1,
			total: 0,
			datas: []
		};

		let {
			page,
			rows,
			group,
			orderby,
			state,
			type,
			order_id,
			begin_time,
			end_time
		} = this.ctx.data;

		const whereObj = {};

		// 状态
		if (state != '全部') {
			whereObj.state_str = state;
		}
		// 类型
		if (type !== '') {
			whereObj['invoice.type'] = type;
		}
		// 订单号
		if (order_id) {
			whereObj.order_id = new RegExp(this.service.utils.filterRegexpKey(order_id), 'i');
		}
		// 申请时间
		if (begin_time && end_time) {
			whereObj.create_time = dbcmd.gte(begin_time).and(dbcmd.lte(end_time));
		}

		// 分组状态数量
		let groupWhereObj = Object.assign({}, whereObj);
		delete groupWhereObj[group.field];

		const groupRes = await this.db.collection('usemall-order-invoice')
			.aggregate()
			.match(groupWhereObj)
			.group({
				_id: '$' + group.field,
				cnt: $.sum(1)
			})
			.end();

		if (groupRes && groupRes.data) {
			response.groupDatas = groupRes.data;
			group.datas = [];
			group.total = 0;

			for (let key in group.obj) {
				group.obj[key] = 0;
			}

			response.groupDatas.forEach(x => {
				if (Object.keys(group.obj).includes(x._id + "")) {
					group.obj[x._id] = x.cnt;
					group.total += x.cnt;
				}
			})
			if (Object.keys(group.obj).includes('全部')) {
				group.obj['全部'] = group.total;
			}

			for (let key in group.obj) {
				group.datas.push({
					name: key,
					cnt: group.obj[key]
				})
			}
			response.group = group;
		}

		// 总数
		const countRes = await this.db.collection('usemall-order-invoice').where(whereObj).count();
		response.total = countRes.total;

		// 排序
		orderby = orderby.split(' ');

		const res = await this.db.collection('usemall-order-invoice')
			.where(whereObj)
			.orderBy(orderby[0], orderby[1])
			.field({
				order_id: true,
				order_amount: true,
				invoice: true,
				invoice_url: true,
				state: true,
				state_str: true,
				create_time: true
			})
			.skip((page - 1) * rows)
			.limit(rows)
			.get();

		const orderIds = res.data.map(x => x.order_id);

		const orderRes = await this.db.collection('usemall-order')
			.where({
				order_id: dbcmd.in(orderIds)
			})
			.orderBy(orderby[0], orderby[1])
			.field({
				order_id: true,
				order_member_name: true,
				order_member_headimg: true,
				invoice_url: true,
				order_info: true,
				state: true
			})
			.get();

		res.data.forEach(x => {
			x.order = orderRes.data.find(o => o.order_id == x.order_id)
		})

		response.code = 0;
		response.datas = res.data;
		return response;
	}

	// 同意
	async consent() {
		const response = {
			code: 1,
			msg: ''
		};

		let {
			id,
			url
		} = this.ctx.data;

		const invoiceRes = await this.db.collection('usemall-order-invoice').doc(id).field({
			order_id: true,
			state_str: true
		}).get();
		const [invoice] = invoiceRes.data;

		if (!invoice) {
			response.msg = '当前数据不存在';
			return response;
		}

		if (invoice.state_str != '申请中') {
			response.msg = `当前状态 ${invoice.state_str}，不可操作`;
			return response;
		}

		await this.db.collection('usemall-order-invoice').doc(id).update({
			state: 1,
			state_str: '已开票',
			invoice_url: url
		})

		await this.db.collection('usemall-order').where({
			order_id: invoice.order_id
		}).update({
			order_invoice_state: 2
		})

		response.code = 0;
		response.msg = '操作成功';
		return response;
	}

	// 拒绝
	async refuse() {
		const response = {
			code: 1,
			msg: ''
		};

		let {
			id,
			remark
		} = this.ctx.data;

		const invoiceRes = await this.db.collection('usemall-order-invoice').doc(id).field({
			order_id: true,
			state_str: true
		}).get();
		const [invoice] = invoiceRes.data;

		if (!invoice) {
			response.msg = '当前数据不存在';
			return response;
		}

		if (invoice.state_str != '申请中') {
			response.msg = `当前状态 ${invoice.state_str}，不可操作`;
			return response;
		}

		await this.db.collection('usemall-order-invoice').doc(id).update({
			state: 2,
			state_str: '已拒绝',
			remark: remark
		})

		await this.db.collection('usemall-order').where({
			order_id: invoice.order_id
		}).update({
			order_invoice_state: 3
		})

		response.code = 0;
		response.msg = '操作成功';
		return response;
	}
}